const logger = require("koa-logger");
const serve = require("koa-static");
const koaBody = require("koa-body");
const Koa = require('koa');
const fs = require("fs");
const app = new Koa();
const os = require("os");
const path = require("path");

const date = require("silly-datetime");
var today = date.format(new Date(),'YYYY-MM-DD');
console.log(today);

app.use(logger());

app.use(koaBody({ multipart: true }));

app.use(serve(path.join(__dirname, '/public')));
app.use(async function (ctx, next) {
	    await next();
	    if (ctx.body || !ctx.idempotent) return;
	    ctx.body = {
              title: '404 not pic'
	    }
})

app.use(async function (ctx, next) {
	    
    if ('POST' != ctx.method) return await next();
    //获取图片源
    const file = ctx.request.files.img;

    //console.log(ctx.request.files);
    console.log(ctx.request.body);
    //接收读出流
    const reader = fs.createReadStream(file.path);
    //创建写入流
    //指定图片路径文件名
    //要重新写
    //console.log(ctx.req);
    //console.log(ctx.request.files.img.name);
    var dirname = file.name.split(".")[0];
    console.log(dirname);
    try {
      if(fs.existsSync("public/images/"+dirname)){
        console.log('文件夹存在');
        const stream = fs.createWriteStream(path.join(`public/images/${dirname}`, file.name));
        reader.pipe(stream);
      }else{
        console.log('文件夹不存在');
        fs.mkdirSync("public/images/"+dirname,app.callback());
        const stream = fs.createWriteStream(path.join(`public/images/${dirname}`, file.name));
	  reader.pipe(stream);
      }
    }catch(e){
      console.log(e);
    }
    //const stream = fs.createWriteStream(path.join('public/images', file.name));
    //用管道将读出流‘倒给’输入流
    //reader.pipe(stream);
    //文件访问路径
    //console.log('uploading %s -> %s', file.name, stream.path);
    //ctx.redirect(stream.path.substr(6).replace(/\\/g,'/'));
})


app.listen(3002, () => {
    console.log("listening port 3002");
})
